import 'package:flutter/material.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// Descriptions: 选择抵扣弹窗
/// [picked] 已选择抵扣
/// [payingAmount] 待支付金额
/// [availablePoints] 可用积分
/// [availableBalance] 可用余额
/// User: tangzhentao
/// Date: 4:58 下午 2021/12/7
///
Future<DeductionPick?> showPickupDeductionDialog({
  required double payingAmount,
  required int availablePoints,
  required double availableBalance,
}) async {
  return await showModalBottomSheet<DeductionPick>(
      context: XfgNav.currentContext,
      isScrollControlled: true,
      isDismissible: false,
      builder: (_) => _PickupDeductionWidget(payingAmount, availablePoints, availableBalance),
  );
}

class _PickupDeductionWidget extends StatefulWidget {
  /// 待支付金额
  final double payingAmount;
  /// 可用积分
  final int availablePoints;
  /// 可用余额
  final double availableBalance;

  const _PickupDeductionWidget(this.payingAmount, this.availablePoints, this.availableBalance);

  @override
  State<StatefulWidget> createState() => _PickupDeductionState();
}

class _PickupDeductionState extends State<_PickupDeductionWidget> {
  /// 待支付金额
  late final double _payingAmount;
  /// 可用积分
  late final int _availablePoints;
  /// 可用余额
  late final double _availableBalance;
  /// 抵扣积分户数量
  int _pointNumber = 0;
  /// 积分抵扣选中
  bool? _pointEnable = false;
  /// 抵扣余额
  double _balanceNumber = 0;
  /// 抵扣余额选中
  bool? _balanceEnable = false;

  @override
  void initState() {
    _payingAmount = widget.payingAmount;
    _availablePoints = widget.availablePoints;
    _availableBalance = widget.availableBalance;
    _pointEnable = _availablePoints > 0 ? false:null;
    _pointNumber = _payingAmount < _availablePoints ? _payingAmount.toInt():_availablePoints;
    _balanceEnable = _availableBalance > 0 ? false:null;
    _balanceNumber = _payingAmount < _availableBalance ? _payingAmount:_availableBalance;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> children = [];
    if (_pointEnable != null) {
      children.add(GestureDetector(
        onTap: () {
          _pointEnable = !_pointEnable!;
          _calMoneyByPointChanged();
        },
        child: Container(
          height: XfgSize().size56,
          padding: EdgeInsets.only(left: XfgSize().size12),
          decoration: _balanceEnable == true ? bottomBorderDecoration:null,
          child: Row(children: [
            xfgRadio(value: _pointEnable!),
            SizedBox(width: XfgSize().size12),
            XfgText('使用$_pointNumber积分，可抵扣', fontSize: XfgSize().text16, color: XfgColor.text1, children: [
              TextSpan(text: '  ¥', style: TextStyle(fontSize: XfgSize().text10, color: XfgColor.itemMoney, fontWeight: FontWeight.bold)),
              TextSpan(text: _pointNumber.toString(), style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.itemMoney, fontWeight: FontWeight.w500)),
            ])
          ]),
        ),
      ));
    }
    if (_balanceEnable != null) {
      children.add(GestureDetector(
        onTap: () {
          _balanceEnable = !_balanceEnable!;
          _calMoneyByBalanceChanged();
        },
        child: Container(
          height: XfgSize().size56,
          padding: EdgeInsets.only(left: XfgSize().size12),
          child: Row(children: [
            xfgRadio(value: _balanceEnable!),
            SizedBox(width: XfgSize().size12),
            XfgText('使用余额积分，可抵扣', fontSize: XfgSize().text16, color: XfgColor.text1, children: [
              TextSpan(text: '  ¥', style: TextStyle(fontSize: XfgSize().text10, color: XfgColor.itemMoney, fontWeight: FontWeight.bold)),
              TextSpan(text: _balanceNumber.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.itemMoney, fontWeight: FontWeight.w500)),
            ])
          ]),
        ),
      ));
    }
    return Material(
      type: MaterialType.transparency,
      child: Container(
        height: XfgSize().size278,
        padding: EdgeInsets.only(bottom: XfgSize().bottomBarHeight),
        decoration: BoxDecoration(color: XfgColor.background, borderRadius: BorderRadius.vertical(top: Radius.circular(XfgSize().size10))),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: XfgSize().size10, vertical: XfgSize().size20),
              alignment: Alignment.topCenter,
              child: Row(
                children: [
                  SizedBox.square(dimension: XfgSize().size24),
                  Expanded(child: XfgText('可用抵扣', fontSize: XfgSize().text20, color: XfgColor.text1D, bold: FontWeight.bold, textAlign: TextAlign.center)),
                  GestureDetector(
                    onTap: XfgNav.pop,
                    child: Icon(Icons.close, size: XfgSize().size24, color: XfgColor.text1),
                  )
                ],
              ),
            ),
            Expanded(child: Column(children: children)),
            SizedBox(height: XfgSize().size10),
            TextButton(
              onPressed: () {
                if (_pointEnable == true || _balanceEnable == true) {
                  XfgNav.pop(DeductionPick(_pointEnable == true ? _pointNumber:0, _balanceEnable == true? _balanceNumber:0));
                } else {
                  XfgNav.pop();
                }
              },
              style: xfgButtonStyle(Size(XfgSize().size170, XfgSize().size50), radius: XfgSize().size50),
              child: XfgText('选择', fontSize: XfgSize().text16, color: XfgColor.white),
            ),
          ],
        ),
      ),
    );
  }

  /// 积分抵扣变化计算金额
  void _calMoneyByPointChanged() {
    double total = _payingAmount;
    _pointNumber = 0;
    _balanceNumber = 0;
    /// 处理余额抵扣
    if (_balanceEnable == true) {
      /// 余额抵扣选中
      _balanceNumber = total < _availableBalance ? total:_availableBalance;
      total = total - _balanceNumber;
      if (total > 0) {
        /// 计算积分抵扣
        _pointNumber = total.toInt() < _availablePoints ? total.toInt():_availablePoints;
      } else {
        _pointEnable = null;
      }
    } else {
      /// 计算积分抵扣
      _pointNumber = total.toInt() < _availablePoints ? total.toInt():_availablePoints;
      if (_pointEnable == true) {
        total = total - _pointNumber;
      }
      if (total > 0) {
        _balanceNumber = total < _availableBalance ? total:_availableBalance;
        _balanceEnable = false;
      } else {
        _balanceEnable = null;
      }
    }
    setState(() {});
  }

  /// 余额抵扣变化计算金额
  void _calMoneyByBalanceChanged() {
    double total = _payingAmount;
    _pointNumber = 0;
    _balanceNumber = 0;
    /// 处理余额抵扣
    if (_pointEnable == true) {
      /// 积分抵扣选中
      _pointNumber = total.toInt() < _availablePoints ? total.toInt():_availablePoints;
      total = total - _pointNumber;
      if (total > 0) {
        /// 计算余额抵扣
        _balanceNumber = total < _availableBalance ? total:_availableBalance;
      } else {
        _balanceEnable = null;
      }
    } else {
      /// 计算余额抵扣
      _balanceNumber = total < _availableBalance ? total:_availableBalance;
      if (_balanceEnable == true) total = total - _balanceNumber;
      if (total > 0) {
        _pointNumber = total.toInt() < _availablePoints ? total.toInt():_availablePoints;
        _pointEnable = false;
      } else {
        _pointEnable = null;
      }
    }
    setState(() {});
  }
}

/// 抵扣选择结果
class DeductionPick {
  /// 抵扣积分户数量
  final int pointNumber;
  /// 抵扣余额
  final double balance;

  DeductionPick(this.pointNumber, this.balance);
}